﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Web.UI;
using System.Web;

namespace TuyennvLibrary.Utl
{
    public class Utilities
    {
        public static void Alert(Page page, System.Type type, string message)
        {
            page.ClientScript.RegisterStartupScript(type, string.Empty, string.Format("<script>alert('{0}')</script>", message));
        }
        public static void Alert(Page page, string message)
        {
            Alert(page, page.GetType(), message);
        }
        public static void Script(Page page, string title, string script)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), title, script);
        }
        public static string PostForm(string url, string postData)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.KeepAlive = false;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string responsedata = reader.ReadToEnd();
                reader.Close();
                return responsedata;
            }
            catch (Exception ex)
            {
            }
            return string.Empty;
        }
        public static string Request(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.KeepAlive = false;
                request.ContentType = "application/x-www-form-urlencoded";
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string responsedata = reader.ReadToEnd();
                reader.Close();
                return responsedata;
            }
            catch (Exception)
            {
            }
            return string.Empty;
        }
        public static string CallWebService(string url, string SOAPAction, string soapRequest)
        {
            WebRequest webRequest = WebRequest.Create(url);
            HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
            httpRequest.Method = "POST";
            httpRequest.ContentType = "text/xml; charset=utf-8";
            httpRequest.Headers.Add("SOAPAction", SOAPAction);
            httpRequest.ProtocolVersion = HttpVersion.Version11;
            httpRequest.Credentials = CredentialCache.DefaultCredentials;
            Stream requestStream = httpRequest.GetRequestStream();
            //Create Stream and Complete Request             
            StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

            streamWriter.Write(soapRequest.ToString());
            streamWriter.Close();
            //Get the Response    
            HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
            StreamReader srd = new StreamReader(wr.GetResponseStream());
            string resulXmlFromWebService = srd.ReadToEnd();
            return resulXmlFromWebService;
        }
        /// <summary>
        /// Mã hóa MD5
        /// </summary>
        /// <param name="input">Chuỗi cần mã hóa</param>
        /// <returns></returns>
        public static string md5(string input)
        {
            MD5 md5Hash = MD5.Create();
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes 
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data  
            // and format each one as a hexadecimal string. 
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string. 
            return sBuilder.ToString();
        }
        public static string getSuccessMessage(string message)
        {
            message = "<font style=\"color: Blue; font-size: 14px; font-weight: bold\">" + message + "</font>";
            return message;
        }
        public static string getErrorMessage(string message)
        {
            message = "<font style=\"color: Red; font-size: 14px; font-weight: bold\">" + message + "</font>";
            return message;
        }
        public static string MapPath(HttpServerUtility Server, string pathFolder)
        {
            return Server.MapPath(pathFolder).Replace("administrator\\", "");
        }
        public static void WriteLog(String message,string pathFolder)
        {
            FileStream _stream;
            try
            {
                String Path = pathFolder + string.Format("{0:yyyy-MM-dd}", DateTime.Now) + ".txt";
                //String Path = HttpContext.Current.Server.MapPath("~/") + "200302.txt";
                if (!File.Exists(Path))
                    _stream = File.Create(Path);
                else
                    _stream = new FileStream(Path, FileMode.Append);

                StreamWriter sw = new StreamWriter(_stream);

                sw.WriteLine(DateTime.Now.ToString() + ":" + message + Environment.NewLine);
                //sw.Flush();
                sw.Close();
                sw.Dispose();
                _stream.Close();
                _stream.Dispose();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// Ghi toàn bộ text của 1 file
        /// </summary>
        /// <param name="path">Đường dẫn tuyệt đối tới file</param>
        /// <returns></returns>
        public static void WriteAllText(string path,string content)
        {
            File.WriteAllText(path, content);
        }
        /// <summary>
        /// Đọc toàn bộ text của 1 file
        /// </summary>
        /// <param name="path">Đường dẫn tuyệt đối tới file</param>
        /// <returns></returns>
        public static string readAllFile(string path)
        {
            string content = File.ReadAllText(path);
            return content;
        }

    }
}
